import { subclass, declared, property } from "esri/core/accessorSupport/decorators";
import Color from "esri/Color";
import esriRequest from "esri/request";

// 引用基础微件类
import BaseTileLayer from "esri/layers/BaseTileLayer";

@subclass("esri.layers.MyTileLayer")
class MyTileLayer extends declared(BaseTileLayer) {
    constructor(prop: any){
        super(prop);
    }

    // 创建urlTemplate，用于解析设置的图层服务地址
    @property()
    urlTemplate: string = "";

    // 创建tint属性，适配Itint接口，用于设置自定义瓦片颜色
    @property()
    tint: Color = null;

    // 覆盖重写getTileUrl，对urlTemplate进行解析替换，使得之后的请求能正确访问所需数据
    getTileUrl(level: number, row: number, col: number) {
        return this.urlTemplate.replace("{z}", level.toString()).replace("{x}", col.toString()).replace("{y}", row.toString());
    }

    // 覆盖重写fetchTile，根据tint属性来设置取回的瓦片数据颜色
    fetchTile(level: number, row: number, col: number) {
        // 获取请求地址，然后对数据发出请求
        const titleUrl = this.getTileUrl(level, row, col);
        return esriRequest(titleUrl, {
            responseType: "image"
        }).then(response => {
            const responseData = response.data;

            // 创建canvas
            const canvasDom = document.createElement("canvas");
            const width = this.tileInfo.size[0];
            const height = this.tileInfo.size[1];
            canvasDom.width = width;
            canvasDom.height = height;

            // 根据数据内容做对应处理
            if (responseData) {
                const context = canvasDom.getContext("2d");

                // 如有传入颜色参数，则修改瓦片颜色
                if (this.tint) {
                    context.fillStyle = this.tint.toCss();
                    context.fillRect(0, 0, width, height);
                    context.globalCompositeOperation = "difference";
                }

                // 将数据绘制于canvas上
                context.drawImage(responseData, 0, 0, width, height);
            }

            return canvasDom;
        });
    }
}

export = MyTileLayer;